package com.tanhua.recommend.msg;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.tanhua.dubbo.pojo.Publish;
import com.tanhua.dubbo.pojo.TimeLine;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RocketMQMessageListener(topic = "timeline_topic", consumerGroup = "timeLineConsumer")
public class TimeLineConsumer implements RocketMQListener<String> {
    // 记录好友列表
    private final static String FREINEDlIST_REDIS = "friend_";
    // 记录上次补偿进度
    private final static String TIMELINE_REDIS = "timeline_";
    // 记录publishId
    private final static String PUBLISH_REDIS = "publish_";
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void onMessage(String publishJson) {

        Publish publish = JSONUtil.toBean(publishJson, Publish.class);
        String timelineRedisKey = this.getTimelineRedisKey(publish.getPid());
        String indexStr = this.redisTemplate.opsForValue().get(timelineRedisKey);
        Integer index = Convert.toInt(indexStr);

        String friendListRedisKey = this.getFriendListRedisKey(publish.getPid());
        String listStr = this.redisTemplate.opsForValue().get(friendListRedisKey);

        List<String> friendIdList = StrUtil.split(listStr, ',');

        String publishRedis = this.getPublishRedis(publish.getPid());
        String idStr = this.redisTemplate.opsForValue().get(publishRedis);
        if (null == idStr) {
            return;
        }
        publish.setId(new ObjectId(idStr));

        for (int i = index; i < friendIdList.size(); i++) {
            TimeLine timeLine = new TimeLine();
            timeLine.setId(ObjectId.get());
            timeLine.setPublishId(publish.getId());
            timeLine.setUserId(publish.getUserId());
            timeLine.setDate(System.currentTimeMillis());
            //写入到好友时间线
            this.mongoTemplate.save(timeLine, "quanzi_time_line_" + friendIdList.get(i));
        }
    }

    private String getTimelineRedisKey(Long pid) {
        return TIMELINE_REDIS + pid;
    }

    private String getFriendListRedisKey(Long pid) {return FREINEDlIST_REDIS + pid;}

    private String getPublishRedis(Long pid) {return PUBLISH_REDIS + pid;}


}
